import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'


// axios前置拦截器
axios.interceptors.request.use(config=>{
  //在所有请求中加入认证token
  let token = window.sessionStorage.getItem('token')
  if(token != null){
    config.headers['Authorization'] = token
  }
  return config
},error=>{
  Promise.reject(error)
})

//axios后置拦截器
axios.interceptors.response.use(response=>{
  //当token快过期时，后台会进行延期处理，生成新的token，前台需更换新的token
  let refToken = response.headers['x-token']
  if(refToken){
    //如果有新的token，则替换原有token
    window.sessionStorage.setItem('token',refToken);
  }
  console.log("后置拦截",response)
  if(response.data.code1==500){
    sessionStorage.removeItem('token');
    sessionStorage.removeItem('userName');
    sessionStorage.removeItem('id');
    sessionStorage.removeItem('loginName')
    alert("操作超时");
    router.push('/login');
  }
  return response;
}
,error=>{
  console.log('后置拦截错误',error.response.data)


  //统一处理服务端的报错
  if(error.response){
    alert(error.response.data.msg);
  }
  return Promise.reject(error);
})


const app = createApp(App)
app.config.globalProperties.axios = axios
app.use(router)
app.use(store)
// app.use(ElementPlus)
app.mount('#app')